package consulTest.common;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static org.springframework.core.Ordered.HIGHEST_PRECEDENCE;


@Slf4j
@ControllerAdvice
//@Order(HIGHEST_PRECEDENCE + 50)
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public Response resolveMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);

        List<ObjectError> objectErrors = e.getBindingResult().getAllErrors();
        if (!CollectionUtil.isEmpty(objectErrors)) {
            StringBuilder msgBuilder = new StringBuilder();
            for (ObjectError objectError : objectErrors) {
                msgBuilder.append(objectError.getDefaultMessage()).append(",");
            }
            String errorMessage = msgBuilder.toString();
            if (errorMessage.length() > 1) {
                errorMessage = errorMessage.substring(0, errorMessage.length() - 1);
            }
            return Response.fail(ResultCode.FAILURE.getCode(), errorMessage);
        }
        return Response.fail(ResultCode.FAILURE.getCode(), e.getMessage());
    }


//    /**
//     * 统一异常拦截，业务异常
//     *
//     * @param request
//     * @param e
//     * @return
//     */
//    @ExceptionHandler(BusinessException.class)
//    @ResponseBody
//    @ResponseStatus(HttpStatus.OK)
//    public Response businessExceptionHandler(HttpServletRequest request, Exception e) {
//        log.error(e.getMessage(), e);
//        return Response.fail(ResultCode.FAILURE.getCode(), e.getMessage());
//    }

    /**
     * 统一异常拦截，业务异常
     *
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public Response defaultExceptionHandler(HttpServletRequest request, Exception e) {
        log.error(e.getMessage(), e);
        return Response.fail(ResultCode.FAILURE, ResultCode.FAILURE.getMessage() + "【" + e.getMessage() + "】");
    }
}
